#include "uart.c"

void timer0_init()
{
    // TIMER1  TIMER0
    // 0000     0000
    // 清除低4位
    // xxxx ????  => xxxx 0000   xxxx ???? & 1111 0000
    // 通过TMOD设置Timer的工作模式
    TMOD &= 0xF0;
    // xxxx xxx1  模式1
    TMOD |= 0x01;
    // 计时器启动，发令枪
    TR0 = 1;
    // 中断使能
    ET0 = 1;
    // 中断总开关
    EA = 1;
    // 为了和uart中断共存，启用一个中断优先级
    PT0 = 1;
}

unsigned int count = 0;
// 中断 ISR
// interrupt service routine
void timer0_ISR() interrupt 1
{
    if (count < 10)
    {
        count++;
    }
    else
    {
        printf("timer0 interrupt!\n");
        count = 0;
    }
}

sbit BTN_TR0 = P2 ^ 0;
sbit BTN_ET0 = P2 ^ 1;
sbit BTN_EA = P2 ^ 2;
sbit BTN_TH_TL = P2 ^ 3;

void main()
{
    uart_init();
    timer0_init();
    while (1)
    {
        if (BTN_TR0 == 0)
        {
            while (BTN_TR0 == 0)
            {
            }

            TR0 = ~TR0;
            // printf 接受int类型的变量，如果只有一个byte，会输出错误内容
            // 必须类型转换到int
            printf("TR0=%d\n", (int)TR0);
        }

        if (BTN_ET0 == 0)
        {
            while (BTN_ET0 == 0)
            {
            }

            ET0 = ~ET0;
            printf("ET0=%d\n", (int)ET0);
        }

        if (BTN_EA == 0)
        {
            while (BTN_EA == 0)
            {
            }

            EA = ~EA;
            printf("EA=%d\n", (int)EA);
        }
        if (BTN_TH_TL == 0)
        {
            while (BTN_TH_TL == 0)
            {
            }
            printf("THTL=0x%04X\n", (unsigned int)(TH0 << 8) | TL0);
        }
    }
}
